// Copyright (c) 2024, cy080585@126.com and contributors
// For license information, please see license.txt
// 动态插入html
// let html = "<div id='item_info_html_grid'> ceshi </div>"

// frm.get_field("item_info_html").$wrapper.html(html)



frappe.ui.form.on("Packing Order", {
    


    // 取消关联单据
    onload: function(frm) {
        // Ignore cancellation for all linked documents of respective DocTypes.
        frm.ignore_doctypes_on_cancel_all = ["Packing List", "Packing List Item"];
        if(frm.doc.docstatus!=0){
            frm.set_df_property('data_import','hidden', 1)
        }
    },

   refresh(frm){
    if (frm.doc.docstatus==1)
    {
       frappe.call({
                method:"zy_packlist.zy_packlist.doctype.packing_order.packing_order.get_packing_order_details",
                args:{
                    packing_order:frm.doc.name,
                    as_dict:true
                },
                callback:function(r){
                    if(r.message){
                        console.log(r.message)
                    frappe.erpnext_excel.download_excel(frm,r.message)
                    }
                }
       })
    } 

    if(frm.doc.docstatus!=1){
        frm.set_df_property('data_import','hidden', 0)
    }


   },


	display_item(frm) {

    frappe.call({
        method:"zy_packlist.zy_packlist.doctype.packing_order.packing_order.get_packing_order_details",
        args:{
            packing_order:frm.doc.name
        },
        callback:function(r){
            console.log(r);
            let head_data=[[__('Marks No.'), 'Item code', 'Descriptions', 'Size/pc (INCH)','Quantities','UOM','Rate','Amount','Net Weight(Kg)/ Sets','Net Weight(Kg)','Gross Weight(Kg)','CTNS','Carton Measure (CM)']]
            // let data=[...hear_data, ...r.message.items]
            // console.log(data);
            erpnext.disply_items(head_data,r.message.items,[0,9,10,11,12])

            // $('#item_info_html_grid').empty();

            // function calculateMergeCells(data, columnIdexs) {
            //     let mergeCells = [];
            //     let preValue = null;
            //     let startRow = 0;
            
            //     data.forEach((row, rowIndex) => {
            //         if (rowIndex === 0) return;        
            //         let currentRowValue = columnIdexs.map(columnIdex => row[columnIdex]).join('');
            
            //         if (currentRowValue !== preValue) {
            //             if (preValue !== null) {
            //                 columnIdexs.forEach(columnIdex => {
            //                     mergeCells.push({ row: startRow, col: columnIdex, rowspan: rowIndex - startRow, colspan: 1 });
            //                 });
            //             }
            //             preValue = currentRowValue;
            //             startRow = rowIndex;
            //         }
            //     });      
            //     // 添加最后一组的合并
            //     if (preValue !== null) {
            //         columnIdexs.forEach(columnIdex => {
            //             mergeCells.push({ row: startRow, col: columnIdex, rowspan: data.length - startRow, colspan: 1 });
            //         });
            //     }
            //     return mergeCells;
            // };
    
            // const container = document.querySelector('#item_info_html_grid');
    
            // //    let data= [  
            // //     [__('Marks No.'), 'Alumibras code', 'Descriptions', 'Size/pc (INCH)', 'NCM','Quantities','Net Weight(Kg)/ Sets','Net Weight(Kg)','Gross Weight(Kg)','CTNS','Carton Measure (CM)'],  
            // //     ['HYQ-1 SA230603946',	'M6S02',	'FRONT TOUCH SCREEN AND LCD DISPLAY M6S02',	6.1 ,	'8517.79.00',	199,	15.084 ,	29.21,	33.35,	1,	'60*46*38'],
            // //     ['HYQ-1 SA230603946',	'M70G1', 'FRONT TOUCH SCREEN AND LCD DISPLAY M70G1',	6.2 ,	'8517.79.00',	96,	5.050 ,	29.21,	33.35,	1	,'60*46*38'],
            // //     ['HYQ-2 SA230603946',	'M6EI2',  'FRONT TOUCH SCREEN AND LCD DISPLAY M6EI2',	6.1,	'8517.79.00',	199,	15.184 ,	34.47,	37.65,	1,	'60*46*38'],
            // //     ['HYQ-2 SA230603946',	'S02AS',  'FRONT TOUCH SCREEN AND LCD DISPLAY S02AS',	6.5 ,	'8517.79.00',	373,	19.284, 	34.47,	37.65,	1,	'60*46*38']
            // //     ]
            //     const hot = new Handsontable(container, {  
            //         data:data,  
            //         rowHeaders: true,  
            //         colHeaders: true,  
            //         autoColumnSize:true,
            //         height: 'auto',  
            //         autoWrapRow: true,  
            //         autoWrapCol: true,  
            //         manualColumnResize:true,
            //         manualRowResize:true,
            //         manualColumnFreeze:true,
            //         licenseKey: 'non-commercial-and-evaluation', // for non-commercial use only  
            //         readOnly:true,
            //         mergeCells:calculateMergeCells(data,[0,9,10,11,12]),
            //         customBorder:true,
            //         className: 'htLeft htMiddle',
            //         rowHeights:26,
            //     });  
            //     console.log(data.length);
            //     $('#item_info_html_grid').css('height', data.length*50+'px');
        }
    })
    },

	// refresh(frm) {

    //     var jQueryDatatableStyle = document.createElement("link");
    //     jQueryDatatableStyle.rel = 'stylesheet';
    //     jQueryDatatableStyle.type = "text/css";
    //     jQueryDatatableStyle.href = "https://unpkg.com/gridjs/dist/theme/mermaid.min.css";
    //     jQueryDatatableStyle.onload = function(){
    //     console.log("jQuery Datatable Style Loaded");
    //     };
    //     document.head.appendChild(jQueryDatatableStyle);

        


    //     $.getScript("https://unpkg.com/gridjs/dist/gridjs.umd.js", function () {

    //         $('#item_info_html_grid').empty();
  
    //           new gridjs.Grid({
    //             columns: ["Name", "Email", "Phone Number"],
    //             data: [
    //               ["John", "john@example.com", "(353) 01 222 3333"],
    //               ["Mark", "mark@gmail.com", "(01) 22 888 4444"],
    //               ["Eoin", "eoin@gmail.com", "0097 22 654 00033"],
    //               ["Sarah", "sarahcdd@gmail.com", "+322 876 1233"],
    //               ["Afshin", "afshin@mail.com", "(353) 22 87 8356"]
    //             ]
    //           }).render(document.getElementById("item_info_html_grid"));

    //     });
	// },


	// refresh(frm) {

    //     var jQueryDatatableStyle = document.createElement("link");
    //     jQueryDatatableStyle.rel = 'stylesheet';
    //     jQueryDatatableStyle.type = "text/css";
    //     jQueryDatatableStyle.href = "https://unpkg.com/tabulator-tables@6.3.0/dist/css/tabulator.min.css";
    //     jQueryDatatableStyle.onload = function(){
    //     console.log("jQuery Datatable Style Loaded");
    //     };
    //     document.head.appendChild(jQueryDatatableStyle);

        


    //     $.getScript("https://unpkg.com/tabulator-tables@6.3.0/dist/js/tabulator.min.js", function () {

    //         $('#item_info_html_grid').empty();
  
    //           //define some sample data
    //         var tabledata = [
    //             {id:1, name:"Oli Bob", age:"12", col:"red", dob:""},
    //             {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"},
    //             {id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"},
    //             {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"},
    //             {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"},
    //         ];

    //         //create Tabulator on DOM element with id "example-table"
    //     var table = new Tabulator("#item_info_html_grid", {
    //         height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
    //         data:tabledata, //assign data to table
    //         layout:"fitColumns", //fit columns to width of table (optional)
    //         columns:[ //Define Table Columns
    //             {title:"Name", field:"name", width:150},
    //             {title:"Age", field:"age", hozAlign:"left", formatter:"progress"},
    //             {title:"Favourite Color", field:"col"},
    //             {title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
    //         ],
    //     });

    //     });
	// },

    data_import(frm){

        if (frm.doc.customer && frm.doc.docstatus==0){
            f_method='zy_packlist.zy_packlist.doctype.packing_order.packing_order.import_parking_order'
            new erpnext.PackingListFile(f_method,(r)=>{
 
                    const savePromises = r.table_head.map(element => {  
                        let row = frm.add_child('items', {  
                            marks_no: element.marks_no,  
                            net_weight_pkg: element.net_weight_pkg,  
                            gross_weight_pkg: element.gross_weight_pkg,  
                            packages_no: element.packages_no,  
                            carton_measure: element.carton_measure,  
                            cbm: element.cbm,  
                        });  
                    
                        return frappe.call({  
                            method: "zy_packlist.zy_packlist.doctype.packing_list.packing_list.add_packing_items_ledgers",  
                            args: {  
                                entries: r.table_body[element.marks_no],  
                                child_row: row,  
                                doc: frm.doc  
                            }  
                        }).then(r => {  
                            let update_values = {  
                                "packing_list_items": r.message.name,  
                                "net_weight_pkg": r.message.net_weight_pkg,  
                                "old_packing_list_items": r.message.name  
                            };  
                            frappe.model.set_value(row.doctype, row.name, update_values);  
                        });  
                    });  
                    
                    Promise.all(savePromises).then(() => {  
                        frm.save();  
                        frm.refresh_field('items');
                    });          
            })

        }else{
            frappe.msgprint(__("No customer selected. Please select a customer"));
        }
        
    },

});


frappe.ui.form.on("Packing Order Item", {

    get_items(frm, cdt, cdn){
        let item = locals[cdt][cdn];
        new erpnext.PackingListItems(
            frm, item,(r) => {
                if (r) {
                    console.log(r);
                    let update_values = {
                        "packing_list_items": r.name,
                         "net_weight_pkg":r.net_weight_pkg,
                         "old_packing_list_items":r.name
                    }
                    // console.log('item.doctype---'+item.doctype +'item.name---'+item.name +'update_values--'+update_values)
                    frappe.model.set_value(item.doctype, item.name, update_values);
                }
            }
        );

    },
    carton_measure(frm, cdt, cdn){
        let row=locals[cdt][cdn];
        if(row.carton_measure){
            const regex = /^\d+\*\d+\*\d+$/;
           if( regex.test(row.carton_measure)){
            
            const regex_out = /\d+/g; 
            let values = row.carton_measure.match(regex_out);
            let cbm = 1;
            values.forEach(element => {
                cbm*=element;
            });
            frappe.model.set_value(row.doctype, row.name, "cbm", cbm/1000000);
           }
           else{
            frappe.msgprint("Invalid format for carton measure. Please use like 100*200*300");
           }         
        }
    },

    gross_weight_pkg(frm, cdt, cdn){
        let row=locals[cdt][cdn];
        if(row.gross_weight_pkg<row.net_weight_pkg){
            frappe.msgprint("The gross weight must be greater than the net weight");
            row.gross_weight_pkg=0;
       }
    },

})
